<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="8" >
            <a-form-model-item label="装车单号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="loadNo">
              <a-input v-model="model.loadNo" placeholder="请输入装车单号" disabled></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="发货通知单" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="noticeNoJoin">
              <j-popup
                v-model="model.noticeNoJoin"
                 field="noticeNoJoin"
                org-fields="notice_no,project_id,contract_no,contract_id,customer_id"
                dest-fields="noticeNoJoin,projectId,contractNo,contractId,customerId"
                code="sd_dispatch_notice_load_popup"
                :multi="true"
                @input="popupCallback"
                />
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="单据日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="billDate">
              <j-date placeholder="请选择单据日期" v-model="model.billDate" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="合同号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="contractNo">
              <a-input v-model="model.contractNo" placeholder="请输入合同号" disabled></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="项目" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="projectId">
              <j-dict-select-tag type="list" v-model="model.projectId" dictCode="quote_project,project_name,id" placeholder="请选择项目" disabled />
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="客户" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="customerId">
              <j-dict-select-tag type="list" v-model="model.customerId" dictCode="crm_customer,cust_full_name,id" placeholder="请选择客户" disabled/>
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="终端客户" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="customerEnd">
              <a-input v-model="model.customerEnd" placeholder="请输入终端客户" disabled></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="车牌号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="carrierCarNo">
              <a-input v-model="model.carrierCarNo" placeholder="请输入车牌号" ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="运费" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="feight">
              <a-input-number v-model="model.feight" placeholder="请输入运费" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="承运单位" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="carrierId">
              <j-search-select-tag v-model="model.carrierId" dict="mdm_supply,supply_full_name,id"  />
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="承运人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="carrierMan">
              <a-input v-model="model.carrierMan" placeholder="请输入承运联系人" ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="承运电话" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="carrierPhone">
              <a-input v-model="model.carrierPhone" placeholder="请输入承运电话" ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="收货地址" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="receiveAddress">
              <a-input v-model="model.receiveAddress" placeholder="请输入收货地址" ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="收货联系人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="receiveMan">
              <a-input v-model="model.receiveMan" placeholder="请输入收货联系人" ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="联系电话" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="receivePhone">
              <a-input v-model="model.receivePhone" placeholder="请输入联系电话" ></a-input>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
      <!-- 子表单区域 -->
    <a-tabs v-model="activeKey" @change="handleChangeTabs">
      <a-tab-pane tab="装车明细" :key="refKeys[0]" :forceRender="true">
        <j-editable-table
          :ref="refKeys[0]"
          :loading="sdDispatchLoadDetailTable.loading"
          :columns="sdDispatchLoadDetailTable.columns"
          :dataSource="sdDispatchLoadDetailTable.dataSource"
          :maxHeight="300"
          :disabled="formDisabled"
          :rowNumber="true"
          :rowSelection="true"
          :actionButton="true"
          :actionAddButton="false"
          @valueChange = "qtyAndPriceChange">
          <div slot="buttonBefore">
            <div class="action-button">
              <a-button type="primary" icon="plus" @click="chooseDispatchDetail" :disabled="formDisabled">选单</a-button>
              <span class="gap"></span>
            </div>
          </div>
        </j-editable-table>
        <j-popup-onl-report
          ref="dispatchDetailPopReport"
          code="sd_dispatch_detail_load_popup"
          multi="true"
          :param="{noticeNoJoin: model.noticeNoJoin, keys: dispatchDetailKeys}"
          @ok="dispatchDetailPopupCallback"/>
      </a-tab-pane>
    </a-tabs>
  </a-spin>
</template>

<script>

  import { getAction } from '@/api/manage'
  import {
    FormTypes,
    getRefPromise,
    getValuesAssign,
    getValuesConcat,
    VALIDATE_NO_PASSED
  } from '@/utils/JEditableTableUtil'
  import { JEditableTableModelMixin } from '@/mixins/JEditableTableModelMixin'
  import { validateDuplicateValue } from '@/utils/util'
  import moment from "moment";

  export default {
    name: 'SdDispatchLoadForm',
    mixins: [JEditableTableModelMixin],
    components: {
    },
    data() {
      return {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 6 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        labelCol2: {
          xs: { span: 24 },
          sm: { span: 3 },
        },
        wrapperCol2: {
          xs: { span: 24 },
          sm: { span: 20 },
        },
        model:{
          status: '01',
          billDate: moment(new Date()).format('YYYY-MM-DD'),
        },
        noticeNoJoinOld: null,
        dispatchDetailKeys: '',
        // 新增时子表默认添加几行空数据
        addDefaultRowNum: 1,
        validatorRules: {
          loadNo: [
            { required: true, message: '请输入装车单号!'},
          ],
           noticeNoJoin: [
              { required: true, message: '请输入发货通知单!'},
           ],
        },
        refKeys: ['sdDispatchLoadDetail', ],
        tableKeys:['sdDispatchLoadDetail', ],
        activeKey: 'sdDispatchLoadDetail',
        // 装车明细
        sdDispatchLoadDetailTable: {
          loading: false,
          dataSource: [],
          columns: [
            {
              title: '物料描述',
              key: 'materialDesc',
              type: FormTypes.popup,
              popupCode:"mdm_popup_bom_material",
              destFields:"materialId,materialNo,materialDesc,unit",
              orgFields:"material_id,material_code,material_desc,unit",
              width:"260px",
              placeholder: '请输入${title}',
              defaultValue:'',
              validateRules: [{ required: true, message: '${title}不能为空' }],
              disabled: true
            },
            {
              title: '单位',
              key: 'unit',
              type: FormTypes.select,
              dictCode:"mdm_unit,unit_name,unit_code",
              width:"110px",
              placeholder: '请输入${title}',
              defaultValue:'',
              disabled: true
            },
            {
              title: '可用库存',
              key: 'stockQtyAvailable',
              type: FormTypes.input,
              width:"140px",
              defaultValue:'0',
              disabled: true
            },
            {
              title: '数量',
              key: 'qty',
              type: FormTypes.inputNumber,
              width:"140px",
              placeholder: '请输入${title}',
              defaultValue:'0',
              validateRules: [
                {required: true, message: '${title}不能为空'},
                {pattern: /^(?!(0[0-9]{0,}$))[0-9]{1,}[.]{0,}[0-9]{0,}$/, message: '请输入大于零的数'},
                {
                  handler(type, value, row, column, callback, target) {
                    let {values} = target.getValuesSync({validate: false, rowIds: [row.id]});
                    if (type === 'blur' || type === 'getValues') {
                      if (value > values[0].stockQtyAvailable) {
                        callback(false, '${title}不能超出可用库存量：' + values[0].stockQtyAvailable)
                        return
                      } else if(value > values[0].unloadQty){
                        callback(false, '${title}不能超出可装车量：' + values[0].unloadQty)
                      }else {
                        callback(true)
                      }
                    } else {
                      callback();
                    }
                  }
                },
              ],
            },
            {
              title: '含税单价',
              key: 'unitPrice',
              type: FormTypes.inputNumber,
              width:"140px",
              placeholder: '请输入${title}',
              defaultValue:'0',
            },
            {
              title: '含税金额',
              key: 'sumPrice',
              type: FormTypes.inputNumber,
              width:"140px",
              placeholder: '请输入${title}',
              defaultValue:'0',
            },
            {
              title: '库房',
              key: 'warehouseId',
              type: FormTypes.sel_search,
              dictCode:"mdm_warehouse,warehouse_name,id",
              width:"140px",
              placeholder: '请输入${title}',
              defaultValue:'',
              disabled: true
            },
            {
              title: '库位',
              key: 'storageLocationId',
              type: FormTypes.sel_search,
              dictCode:"mdm_storage_location,location_name,id",
              width:"140px",
              placeholder: '请输入${title}',
              defaultValue:'',
              disabled: true
            },
            {
              title: '批次',
              key: 'batchNo',
              type: FormTypes.input,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
              disabled: true
            },
            {
              title: '备注',
              key: 'remark',
              type: FormTypes.input,
              width:"240px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '通知单号',
              key: 'noticeNo',
              type: FormTypes.input,
              width:"140px",
              placeholder: '请输入${title}',
              defaultValue:'',
              disabled: true
            },
            {
              title: '通知单行号',
              key: 'dispatchDetailLineNo',
              type: FormTypes.input,
              width:"90px",
              placeholder: '请输入${title}',
              defaultValue:'',
              disabled: true
            },
            {
              title: '销售单号',
              key: 'salesOrderNo',
              type: FormTypes.input,
              width:"140px",
              placeholder: '请输入${title}',
              defaultValue:'',
              disabled: true
            },
            {
              title: '销售单行号',
              key: 'salesDetailLineNo',
              type: FormTypes.input,
              width:"90px",
              placeholder: '请输入${title}',
              defaultValue:'',
              disabled: true
            },
            {
              title: '销售明细ID',
              key: 'salesDetailId',
              type: FormTypes.hidden,
            },
            {
              title: '发货明细ID',
              key: 'dispatchDetailId',
              type: FormTypes.hidden,
            },
            {
              title: 'materialId',
              key: 'materialId',
              type: FormTypes.hidden,
            },
            {
              title: 'materialNo',
              key: 'materialNo',
              type: FormTypes.hidden,
            },
            {
              title: 'materialStockId',
              key: 'materialStockId',
              type: FormTypes.hidden,
            },
            {
              title: 'unloadQty',
              key: 'unloadQty',
              type: FormTypes.hidden,
            },
          ]
        },
        url: {
          add: "/sd/dispatchLoad/add",
          edit: "/sd/dispatchLoad/edit",
          queryById: "/sd/dispatchLoad/queryById",
          sdDispatchLoadDetail: {
            list: '/sd/dispatchLoad/querySdDispatchLoadDetailStockByMainId'
          },
        }
      }
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    computed: {
      formDisabled(){
        return this.disabled
      },
    },
    created () {
    },
    methods: {
      addBefore(){
        this.genBillNo("31","loadNo");
        this.sdDispatchLoadDetailTable.dataSource=[]
      },
      getAllTable() {
        let values = this.tableKeys.map(key => getRefPromise(this, key))
        return Promise.all(values)
      },
      /** 调用完edit()方法之后会自动调用此方法 */
      editAfter() {
        this.$nextTick(() => {
          this.noticeNoJoinOld = this.model.noticeNoJoin
        })
        // 加载子表数据
        if (this.model.id) {
          let params = { id: this.model.id }
          this.requestSubTableData(this.url.sdDispatchLoadDetail.list, params, this.sdDispatchLoadDetailTable)
        }
      },
      //校验所有一对一子表表单
      validateSubForm(allValues){
          return new Promise((resolve,reject)=>{
            Promise.all([
            ]).then(() => {
              resolve(allValues)
            }).catch(e => {
              if (e.error === VALIDATE_NO_PASSED) {
                // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
                this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
              } else {
                console.error(e)
              }
            })
          })
      },
      /** 整理成formData */
      classifyIntoFormData(allValues) {
        let main = Object.assign(this.model, allValues.formValue)
        return {
          ...main, // 展开
          sdDispatchLoadDetailList: allValues.tablesValue[0].values,
        }
      },
      validateError(msg){
        this.$message.error(msg)
      },
     popupCallback(value,row){
       let obj = {noticeNoJoin: null, contractNo: null,contractId: null, projectId: null, customerId: null}
        // 合同
        if(row.contractNo){
          let contractNoArr = []
          row.contractNo.split(',').forEach(item=>{
            if(!contractNoArr.includes(item)){
              contractNoArr.push(item);
            }
          })
          if(contractNoArr.length > 1){
            this.$message.error("不同合同不可以装一车！")
            obj.noticeNoJoin = this.noticeNoJoinOld
            this.$nextTick(()=> {
              this.model = Object.assign(this.model, obj);
            })
            return
          }
          if(contractNoArr.length == 1){
            obj.contractNo = contractNoArr[0];
            obj.contractId = row.contractId.split(',')[0];
          }
        }
        // 项目
       if(row.projectId){
         let projectIdArr = []
         row.projectId.split(',').forEach(item=>{
           if(!projectIdArr.includes(item)){
             projectIdArr.push(item);
           }
         })
         if(projectIdArr.length > 1){
           this.$message.error("不同项目不可以装一车！")
           obj.noticeNoJoin = this.noticeNoJoinOld
           this.$nextTick(()=> {
             this.model = Object.assign(this.model, obj);
           })
           return
         }
         if(projectIdArr.length == 1){
           obj.projectId = projectIdArr[0];
         }
       }
       // 客户
       if(row.customerId){
         let customerIdArr = []
         row.customerId.split(',').forEach(item=>{
           if(!customerIdArr.includes(item)){
             customerIdArr.push(item);
           }
         })
         if(customerIdArr.length > 1){
           this.$message.error("不同客户不可以装一车！")
           obj.noticeNoJoin = this.noticeNoJoinOld
           this.$nextTick(()=> {
             this.model = Object.assign(this.model, obj);
           })
           return
         }
         if(customerIdArr.length == 1){
           obj.customerId = customerIdArr[0];
         }
       }
       obj.noticeNoJoin = value;
       this.noticeNoJoinOld = value;
       this.model = Object.assign(this.model, obj);
     },
      qtyAndPriceChange(parm){
        if(parm && parm['column'] && parm['row'] && parm['target']){
          let cols = ['qty','unitPrice','sumPrice'];
          let key = parm.column.key;
          if(cols.includes(key) && !this.qtyAndPriceModifyFlag){
            let valueObj = {}
            let editableTable = parm['target'];
            let qty = Number(parm.row[cols[0]] || 0);
            //修改数量
            if(key === cols[0]){
              //计算金额
              let unitPrice = parm.row[cols[1]] || 0;
              let sumPrice = Math.round(unitPrice * qty * 100)/100;
              //
              valueObj = {[cols[2]]: sumPrice}
            }
            // 修改单价、金额
            if(key === cols[1] || key === cols[2]){
              let unitPrice, sumPrice
              if(key === cols[1]){
                //计算金额
                unitPrice = parm.row[cols[1]] || 0;
                sumPrice = Math.round(unitPrice * qty * 100)/100;
              }
              if(key === cols[2]){
                //计算单价
                sumPrice = parm.row[cols[2]] || 0;
                unitPrice = qty == 0 ? 0 : Math.round(sumPrice / qty * 100)/100;
              }
              //
              valueObj = {[cols[1]]: unitPrice,[cols[2]]: sumPrice}
            }
            //更新
            this.qtyAndPriceModifyFlag = true
            editableTable.setValues([{rowKey: parm.row.id, values: valueObj}]);
            this.qtyAndPriceModifyFlag = false
            // 重新计算统计列
            // editableTable.recalcOneStatisticsColumn(cols[2]);
            // editableTable.recalcOneStatisticsColumn(cols[4]);
          }
        }
      },
      chooseDispatchDetail() {
        if (!this.model.noticeNoJoin) {
          this.$message.error("请先选择发货通知单！")
          return
        }
        let dispatchLoadDetailTable = this.$refs[this.refKeys[0]];
        let valArr = getValuesConcat(dispatchLoadDetailTable, ['dispatchDetailId','materialStockId']);
        if(valArr.length > 0){
          this.dispatchDetailKeys = valArr.join(',');
        }else{
          this.dispatchDetailKeys = '';
        }
        this.$refs.dispatchDetailPopReport.show();
      },
      dispatchDetailPopupCallback(rows){
        if(rows && rows.length > 0){
          let dispatchLoadDetailTable = this.$refs[this.refKeys[0]];
          let oldData = dispatchLoadDetailTable.getValuesSync();
          let column = this.sdDispatchLoadDetailTable.columns.find(col=>col.key === 'materialDesc')
          let orgFieldsArr = ['material_id','material_no','material_desc','unit','unit_price','warehouse_id','storage_location_id','batch_no','unload_qty',
            'sales_detail_id','sales_order_no','sales_detail_line_no','line_no','notice_no','id','stock_qty_available','material_stock_id','sum_price'];
          let destFieldsArr = ['materialId','materialNo','materialDesc','unit','unitPrice','warehouseId','storageLocationId','batchNo','unloadQty',
            'salesDetailId','salesOrderNo','salesDetailLineNo','dispatchDetailLineNo','noticeNo','dispatchDetailId','stockQtyAvailable','materialStockId','sumPrice'];
          let addRow, addData
          for(let i =0; i< rows.length; i++){
            if(!(i === 0 && oldData && oldData.values && oldData.values.length===1 && !oldData.values[0].materialDesc)){
              dispatchLoadDetailTable.add();
            }
            addRow = dispatchLoadDetailTable.rows[dispatchLoadDetailTable.rows.length - 1];
            // key转换
            for(let j=0; j<orgFieldsArr.length; j++){
              rows[i][destFieldsArr[j]] = rows[i][orgFieldsArr[j]];
              if(destFieldsArr[j] !== orgFieldsArr[j]){
                delete rows[i][orgFieldsArr[j]]
              }
            }
            addData = Object.assign({},rows[i])
            dispatchLoadDetailTable.popupCallback(addData.materialDesc, addData, 'materialDesc'+addRow.id, addRow, column)
          }
        }
      },
    }
  }
</script>

<style scoped>
.action-button {
  margin-bottom: 8px;
}

.gap {
  padding-left: 8px;
}
</style>